package com.imstlife.vending.sgy.logger;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@SuppressLint({"SimpleDateFormat", "SdCardPath"})
public class LocalLog {

    private static Boolean LOG_WRITE_TO_FILE = true; // 日志写入文件开关
    private static int LOG_FILE_MAX = 20; // 日志文件的最多保存个数,
    private static String LOG_FILE_EXT = ".txt"; // 本类输出的日志文件名称
    private static String LOG_FILE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mydoor/"; // 日志文件在sdcard中的路径
    private static SimpleDateFormat LogSdf; // 日志的输出格式
    private static SimpleDateFormat logfile; // 日志文件格式
    private static boolean init = false;


    /**
     * 初始化本地日志配置
     *
     * @param writeFile 是否写入本地
     * @param num       最大存储文件数量
     * @param pathName  日志文件夹名字
     */
    public static void init(boolean writeFile, int num, String pathName) {
        LOG_WRITE_TO_FILE = writeFile;
        LOG_FILE_MAX = num;
        LOG_FILE_DIR = "/sdcard/" + pathName + "/"; // 日志文件在sdcard中的路径
        init();
    }

    private static void init() {
        init = true;
        LogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logfile = new SimpleDateFormat("yyyyMMdd");
        LogSdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        logfile.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        File logDir = new File(LOG_FILE_DIR);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        File logDir2 = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/imstlife/zip/");
        if (!logDir2.exists()) {
            logDir2.mkdirs();
        }
        delFile();
    }

    /**
     * verbose模式,打印最详细的日志
     *
     * @param tag  标签
     * @param text 内容
     */
    public static void v(String tag, String text) {
        writeLog(tag, text, 'v');
    }

    /**
     * debug的日志
     *
     * @param tag  标签
     * @param text 内容
     */
    public static void d(String tag, String text) {
        writeLog(tag, text, 'd');
    }

    /**
     * info的日志
     *
     * @param tag  标签
     * @param text 内容
     */
    public static void i(String tag, String text) {
        writeLog(tag, text, 'i');
    }

    /**
     * warn的日志
     *
     * @param tag  标签
     * @param text 内容
     */
    public static void w(String tag, String text) {
        writeLog(tag, text, 'w');
    }

    /**
     * error的日志
     *
     * @param tag  标签
     * @param text 内容
     */
    public static void e(String tag, String text) {
        writeLog(tag, text, 'e');
    }

    //输出日志
    private static void writeLog(String tag, String msg, char level) {
        if ('d' == level) {
            Log.d(tag, msg);
        } else if ('i' == level) {
            Log.i(tag, msg);
        } else if ('e' == level) {
            Log.e(tag, msg);
        } else if ('w' == level) {
            Log.w(tag, msg);
        } else {
            Log.v(tag, msg);
        }

        if (LOG_WRITE_TO_FILE)
            writeLogToFile(String.valueOf(level), tag, msg);
    }

    /**
     * 写入文件
     *
     * @param type
     * @param tag
     * @param text
     */
    private static synchronized void writeLogToFile(String type, String tag, String text) {
        if (!init)
            init();
        Date time = new Date();
        String fileName = logfile.format(time);
        String logMsg = LogSdf.format(time) + " Log." + type + " " + tag + " " + text;
        File file = new File(LOG_FILE_DIR, fileName + LOG_FILE_EXT);
        try {
            FileWriter filerWriter = new FileWriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
            bufWriter.write(logMsg);
            bufWriter.newLine();
            bufWriter.close();
            filerWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断最大日志个数是否大于最大个数，如果是的则删除最小的那个日志
     */
    public static void delFile() {
        File file = new File(LOG_FILE_DIR);
        File[] files = file.listFiles();
        if (files != null && files.length > LOG_FILE_MAX) {
            String fileName = files[0].getName();
            int temp = Integer.valueOf(fileName.substring(0,
                    fileName.indexOf(".")).replace("-", ""));
            int min = temp;
            String minName = fileName;
            for (int i = 0; i < files.length; i++) {
                fileName = files[i].getName();
                temp = Integer.valueOf(fileName.substring(0,
                        fileName.indexOf(".")).replace("-", ""));
                if (temp <= min) {
                    min = temp;
                    minName = fileName; // 保存文件名
                }
            }
            if (!"".equals(minName)) {
                file = new File(LOG_FILE_DIR, minName);
                if (file.exists())
                    file.delete();
            }
        }
    }



    /**
     * 获取要上传的文件(zip)
     *
     * @param fileName 目标日志文件名，格式：20190319
     * @return
     */
    private static String getUploadFile(String fileName, String deviceId) {
        String filePath = LOG_FILE_DIR + fileName + LOG_FILE_EXT;
        String ZipFilePath = LOG_FILE_DIR + deviceId + "-" + fileName + ".zip";
        File file = new File(filePath);
        File zipFile = new File(ZipFilePath);
        if (file.exists()) {
            if (zipFile.exists())
                zipFile.delete();
            try {
                ZipUtils.zipFile(file, zipFile);
                return zipFile.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getUploadFile2(List<String> listfileinfo , String fileName, String deviceId) {
        LocalLog.d("log", "日志操作 获取目标日志文件");
        String ZipFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/imstlife/zip/" + deviceId + "-" + fileName + ".zip";
        File zipFile = new File(ZipFilePath);
        if (zipFile.exists())
            zipFile.delete();
        List<String> list = new ArrayList<>();
        for (int i=0;i<listfileinfo.size();i++){
            File file = new File(listfileinfo.get(i));
            if (file.exists()){
                list.add(listfileinfo.get(i));
            }
        }
        try {
            ZipUtils.zipFiles(list, ZipFilePath);
            return zipFile.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
